package web.servlet;

import domain.Account;
import domain.Cart;
import domain.Order;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import persistence.OrderDao;
import service.OrderService;

import java.io.IOException;

public class OrderFormServlet extends HttpServlet {
    //将所有订单插入到数据库中，跳转到最后的展示页面
    private static final String VIEW_ORDER = "/WEB-INF/jsp/order/ViewOrder.jsp";

//    @Override
//    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        this.doPost(req,resp);
//    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Order order = (Order) session.getAttribute("currentOrder");//获取页面中保存的订单
        Cart cart = (Cart)  session.getAttribute("cart");
        if (order != null) {
            OrderService orderService = new OrderService();

            //将确认后的订单插入数据库
            orderService.insertOrder(order);

            //清空购物车
            String userid = (String) session.getAttribute("username");
            cart = new Cart();
            cart.removeItemById(userid);
            String workingItemId = null;
            session.setAttribute("cart", cart);
            session.setAttribute("workingItemId", workingItemId);

            String message = "Thank you, your order has been submitted.";
            session.setAttribute("message", message);

            req.getRequestDispatcher(VIEW_ORDER).forward(req, resp);
        }
    }
}
